import mitt from 'mitt';
import { onUnmounted } from 'vue';

// 1. 先写事件字典，后期可随意追加
type Events = {
  'open:post': any;
  // 通配符写法，也可 [k: string]: any
  'detail:comment': any;
  'detail:isLike': any;
};

// 2. 导出带类型的 emitter
export const bus = mitt<Events>();

// 3. 封装「自动 off」工具函数，后面组件直接调用
export function useBus() {
  const handlers: Array<() => void> = [];

  const on = <K extends keyof Events>(event: K, handler: (arg: Events[K]) => void) => {
    bus.on(event, handler as any);
    handlers.push(() => bus.off(event, handler as any));
  };

  const once = <K extends keyof Events>(event: K, handler: (arg: Events[K]) => void) => {
    const wrapped = (arg: Events[K]) => {
      handler(arg);
      bus.off(event, wrapped as any);
    };
    bus.on(event, wrapped as any);
  };

  const emit = <K extends keyof Events>(event: K, arg?: Events[K]) => bus.emit(event, arg as any);

  // 生命周期统一清理
  onUnmounted(() => handlers.forEach((h) => h()));

  return { on, once, emit };
}
